# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

# 引入pymysql模块
import pymysql
from movie.settings import MYSQL_CHARSET, MYSQL_DB_NAME, MYSQL_HOST, MYSQL_PASSWORD, MYSQL_USER
import pymysql.cursors

class MoviePipeline(object):

    def __init__(self):
        # 连接数据库
        self.connect = pymysql.connect(
            host=MYSQL_HOST,
            db=MYSQL_DB_NAME,
            user=MYSQL_USER,
            password=MYSQL_PASSWORD,
            charset=MYSQL_CHARSET,
            use_unicode=True
        )
        # 通过cursor执行增删改查
        self.cursor = self.connect.cursor()

    def process_item(self, item, spider):
        try:
            # 插入语句
            self.cursor.execute("""
                insert into scrapy(name) values (%s)
            """, (
                item['name']
            ))
            # 提交sql
            self.connect.commit()
        except Exception as error:
            print(error)
        return item
